import { defineStore } from 'pinia';
import { GiftBook, GiftRecord, GiftRecordType } from '@/types/giftbook';
import { nanoid } from '@/utils/nanoid-polyfill';

interface GiftBookState {
  giftBooks: GiftBook[];
  currentGiftBook: GiftBook | null;
  loading: boolean;
  error: string | null;
  receiveAmountMap: Map<string, number>;
  giveAmountMap: Map<string, number>;
  contactRecordsMap: Map<string, GiftRecord[]>;
}

export const useGiftBookStore = defineStore('giftbook', {
  state: (): GiftBookState => ({
    giftBooks: [],
    currentGiftBook: null,
    loading: false,
    error: null,
    receiveAmountMap: new Map(),
    giveAmountMap: new Map(),
    contactRecordsMap: new Map()
  }),

  getters: {
    // 获取所有礼簿
    getAllGiftBooks: (state) => state.giftBooks,
    
    // 获取当前礼簿
    getCurrentGiftBook: (state) => state.currentGiftBook,
    
    // 按类型获取礼簿
    getGiftBooksByType: (state) => (type: string) => {
      return state.giftBooks.filter((book: GiftBook) => book.type === type);
    },

    // 获取联系人收礼总额
    getContactReceiveAmount: (state) => (contactId: string) => {
      return state.receiveAmountMap.get(contactId) || 0;
    },

    // 获取联系人送礼总额
    getContactGiveAmount: (state) => (contactId: string) => {
      return state.giveAmountMap.get(contactId) || 0;
    },

    // 获取联系人往来记录
    getContactRecords: (state) => (contactId: string) => {
      return state.contactRecordsMap.get(contactId) || [];
    },

    // 获取联系人往来次数
    getContactRecordCount: (state) => (contactId: string) => {
      const records = state.contactRecordsMap.get(contactId);
      return records ? records.length : 0;
    }
  },

  actions: {
    // 更新联系人金额统计和往来记录
    updateAmountMaps() {
      const receiveMap = new Map<string, number>();
      const giveMap = new Map<string, number>();
      const recordsMap = new Map<string, GiftRecord[]>();

      console.log('【礼簿】开始更新联系人映射');
      
      // 遍历所有礼簿和记录
      this.giftBooks.forEach(book => {
        book.records.forEach(record => {
          const { contactId, type, amount } = record;
          
          if (!contactId) {
            console.warn('【礼簿】发现没有contactId的记录:', record);
            return; // 跳过没有contactId的记录
          }
          
          const numAmount = Number(amount) || 0;

          // 更新金额统计
          if (type === 'receive') {
            const currentAmount = receiveMap.get(contactId) || 0;
            receiveMap.set(contactId, currentAmount + numAmount);
          } else if (type === 'give') {
            const currentAmount = giveMap.get(contactId) || 0;
            giveMap.set(contactId, currentAmount + numAmount);
          }

          // 更新联系人往来记录
          const contactRecords = recordsMap.get(contactId) || [];
          contactRecords.push({...record}); // 添加记录的副本
          recordsMap.set(contactId, contactRecords);
        });
      });

      // 为每个联系人的记录按时间排序（从新到旧）
      recordsMap.forEach((records, contactId) => {
        recordsMap.set(
          contactId,
          records.sort((a, b) => {
            // 优先用createTime排序
            const timeA = a.createTime || 0;
            const timeB = b.createTime || 0;
            return timeB - timeA;
          })
        );
      });

      // 打印调试信息
      console.log(`【礼簿】更新完成，共有 ${recordsMap.size} 个联系人的往来记录`);
      recordsMap.forEach((records, contactId) => {
        console.log(`【礼簿】联系人 ${contactId} 有 ${records.length} 条往来记录`);
      });

      // 更新状态
      this.receiveAmountMap = receiveMap;
      this.giveAmountMap = giveMap;
      this.contactRecordsMap = recordsMap;
    },

    // 添加礼簿
    addGiftBook(giftBook: Partial<GiftBook>) {
      const newGiftBook = this.validateGiftBook({
        ...giftBook,
        id: nanoid(),
        records: [],
        totalReceived: 0,
        totalGiven: 0,
        createTime: Date.now(),
        updateTime: Date.now()
      });
      
      this.giftBooks.push(newGiftBook);
      this.saveToStorage();
      return newGiftBook.id;
    },

    // 更新礼簿
    updateGiftBook(giftBook: GiftBook) {
      const index = this.giftBooks.findIndex(book => book.id === giftBook.id);
      if (index !== -1) {
        this.giftBooks[index] = {
          ...giftBook,
          updateTime: Date.now()
        };
        this.saveToStorage();
      }
    },

    // 删除礼簿
    deleteGiftBook(id: string) {
      this.giftBooks = this.giftBooks.filter(book => book.id !== id);
      this.saveToStorage();
    },

    // 设置当前礼簿
    setCurrentGiftBook(giftBook: GiftBook | null) {
      console.log('Store: 设置当前礼簿:', giftBook);
      this.currentGiftBook = giftBook ? { ...giftBook } : null;
    },

    // 更新当前礼簿
    updateCurrentGiftBook() {
      if (this.currentGiftBook) {
        const giftBook = this.giftBooks.find((book: GiftBook) => book.id === this.currentGiftBook?.id);
        if (giftBook) {
          this.currentGiftBook = { ...giftBook };
        }
      }
    },

    // 计算并更新礼簿的收入支出总额
    updateGiftBookTotals(giftBookId: string) {
      const giftBook = this.giftBooks.find((book: GiftBook) => book.id === giftBookId);
      if (giftBook) {
        let totalReceived = 0;
        let totalGiven = 0;
        
        giftBook.records.forEach((record: GiftRecord) => {
          const amount = Number(record.amount) || 0;
          if (record.type === 'receive') {
            totalReceived += amount;
          } else if (record.type === 'give') {
            totalGiven += amount;
          }
        });
        
        giftBook.totalReceived = totalReceived;
        giftBook.totalGiven = totalGiven;
        giftBook.updateTime = Date.now();
        
        this.saveToStorage();
        this.updateCurrentGiftBook();
      }
    },

    // 修改 addGiftRecord 方法，添加对总额的更新
    addGiftRecord(giftBookId: string, record: GiftRecord) {
      const giftBook = this.giftBooks.find((book: GiftBook) => book.id === giftBookId);
      if (giftBook) {
        giftBook.records.push(record);
        giftBook.updateTime = Date.now();
        this.updateGiftBookTotals(giftBookId);
        this.updateCurrentGiftBook();
      }
    },

    // 修改 updateGiftRecord 方法，添加对总额的更新
    updateGiftRecord(giftBookId: string, record: GiftRecord) {
      const giftBook = this.giftBooks.find((book: GiftBook) => book.id === giftBookId);
      if (giftBook) {
        const index = giftBook.records.findIndex((r: GiftRecord) => r.id === record.id);
        if (index !== -1) {
          // 保留原有记录的createTime，如果原有记录的createTime为空，则使用当前时间
          const originalRecord = giftBook.records[index];
          const now = Date.now();
          giftBook.records[index] = {
            ...record,
            createTime: originalRecord.createTime || now // 如果原有记录的createTime为空，则使用当前时间
          };
          giftBook.updateTime = Date.now();
          this.updateGiftBookTotals(giftBookId);
          this.updateCurrentGiftBook();
        }
      }
    },

    // 修改 deleteGiftRecord 方法，添加对总额的更新
    deleteGiftRecord(giftBookId: string, recordId: string) {
      const giftBook = this.giftBooks.find((book: GiftBook) => book.id === giftBookId);
      if (giftBook) {
        giftBook.records = giftBook.records.filter((r: GiftRecord) => r.id !== recordId);
        giftBook.updateTime = Date.now();
        this.updateGiftBookTotals(giftBookId);
        this.updateCurrentGiftBook();
      }
    },

    // 从存储加载数据
    async loadFromStorage() {
      try {
        console.log('Store: 开始从存储加载礼簿数据');
        const data = uni.getStorageSync('giftbooks');
        console.log('Store: 从存储读取的原始数据:', data);
        
        if (data) {
          try {
            const parsedData = JSON.parse(data);
            console.log('Store: 解析后的数据:', parsedData);
            
            // 转换数据确保符合GiftBook接口
            if (Array.isArray(parsedData)) {
              this.giftBooks = parsedData.map((book) => this.validateGiftBook(book));
            } else {
              console.log('Store: 数据不是数组，初始化为空数组');
              this.giftBooks = [];
            }
          } catch (parseError) {
            console.error('Store: JSON解析失败:', parseError);
            this.giftBooks = [];
          }
        } else {
          console.log('Store: 存储中没有礼簿数据，初始化为空数组');
          this.giftBooks = [];
        }
        this.updateAmountMaps();
      } catch (error) {
        console.error('Store: 加载礼簿数据失败:', error);
        this.giftBooks = [];
      }
    },

    // 验证并修复GiftBook数据
    validateGiftBook(book: any): GiftBook {
      // 创建一个基础的GiftBook对象
      const validBook: GiftBook = {
        id: book.id || nanoid(),
        title: book.title || '未命名礼簿',
        type: book.type || 'other',
        date: book.date || new Date().toISOString().split('T')[0],
        records: [],
        totalReceived: 0,
        totalGiven: 0,
        createTime: book.createTime || Date.now(),
        updateTime: book.updateTime || Date.now()
      };
      
      // 复制可选字段
      if (book.location) validBook.location = book.location;
      if (book.description) validBook.description = book.description;
      if (book.totalReceived !== undefined) validBook.totalReceived = Number(book.totalReceived);
      if (book.totalGiven !== undefined) validBook.totalGiven = Number(book.totalGiven);
      
      // 验证和转换records
      if (Array.isArray(book.records)) {
        validBook.records = book.records.map((record: any) => this.validateGiftRecord(record));
        
        // 重新计算总收入和总支出
        let totalReceived = 0;
        let totalGiven = 0;
        
        validBook.records.forEach((record: GiftRecord) => {
          const amount = Number(record.amount) || 0;
          if (record.type === 'receive') {
            totalReceived += amount;
          } else if (record.type === 'give') {
            totalGiven += amount;
          }
        });
        
        validBook.totalReceived = totalReceived;
        validBook.totalGiven = totalGiven;
      }
      
      return validBook;
    },

    // 验证并修复GiftRecord数据
    validateGiftRecord(record: any): GiftRecord {
      const now = Date.now();
      return {
        id: record.id || nanoid(),
        giftBookId: record.giftBookId || '',
        contactId: record.contactId || '',
        contactName: record.contactName || '',
        type: record.type || GiftRecordType.OTHER,
        amount: Number(record.amount) || 0,
        giftName: record.giftName,
        remarks: record.remarks,
        createTime: typeof record.createTime !== 'undefined' ? record.createTime : now,
        updateTime: record.updateTime || now
      };
    },

    // 保存数据到存储
    async saveToStorage() {
      try {
        console.log('Store: 准备保存礼簿数据:', this.giftBooks);
        uni.setStorageSync('giftbooks', JSON.stringify(this.giftBooks));
        console.log('Store: 礼簿数据保存成功');
        this.updateAmountMaps();
      } catch (error) {
        console.error('Store: 保存礼簿数据失败:', error);
      }
    },
  },
}); 